import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/base/base_state.dart';
import 'package:flutter_app/constant.dart';
import 'package:flutter_app/http/http_manager.dart';
import 'package:flutter_app/model/article_resp.dart';
import 'package:flutter_app/model/author_resp.dart';
import 'package:flutter_app/model/banner_resp.dart';
import 'package:flutter_app/model/project_resp.dart';
import 'package:flutter_app/pages/list_article_item.dart';
import 'package:flutter_app/provider/common_provider.dart';
import 'package:flutter_app/res/colours.dart';
import 'package:flutter_app/res/strings.dart';
import 'package:flutter_app/routers/router_utils.dart';
import 'package:flutter_app/utils/http_utils.dart';
import 'package:flutter_app/widget/banner_page.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:provider/provider.dart';

class PiazzaPage extends BaseFulWidget {
  @override
  State<StatefulWidget> createState() => _PiazzaState();
}

class _PiazzaState extends State<PiazzaPage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  CommonProvider _bannerProvider = CommonProvider<BannerBean>();
  CommonProvider _projectProvider = CommonProvider<ProjectBean>();
  CommonProvider _authorProvider = CommonProvider<AuthorBean>();
  CommonProvider _articleProvider = CommonProvider<ArticleBean>();

  @override
  void initState() {
    super.initState();
    _requestBanner();
    _requestProject();
    _requestAuthor();
    _requestHotArticle();
  }

  ///请求banner数据
  void _requestBanner() {
    HttpManager()
        .getAsync(url: Constant.API_BANNER, tag: Constant.API_BANNER)
        .then((value) {
      List<BannerBean> list =
          value.map<BannerBean>((json) => BannerBean.fromJson(json)).toList();
      _bannerProvider.setDataList(list);
    });
  }

  ///请求项目列表数据
  void _requestProject() {
    HttpUtils.httpUtils.getRequest(Constant.API_PROJECT).then((value) {
      var model = ProjectResp.fromJson(value.data);
      _projectProvider.setDataList(model.data.datas);
    });
  }

  ///请求公众号列表数据
  void _requestAuthor() {
    HttpUtils.httpUtils.getRequest(Constant.API_AUTHOR).then((value) {
      var model = AuthorResp.fromJson(value.data);
      _authorProvider.setDataList(model.data);
    });
  }

  ///请求首页文章
  void _requestHotArticle() {
    HttpUtils.httpUtils.getRequest(Constant.API_HOT_ARTICLE).then((value) {
      var model = ArticleResp.fromJson(value.data);
      _articleProvider.setDataList(model.data.datas);
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Colours.fff1f3f4,
      body: SingleChildScrollView(
        child: Stack(
          children: [
            MultiProvider(
              providers: [
                ChangeNotifierProvider(create: (_) => _bannerProvider),
                ChangeNotifierProvider(create: (_) => _projectProvider),
                ChangeNotifierProvider(create: (_) => _authorProvider),
                ChangeNotifierProvider(create: (_) => _articleProvider),
              ],
              child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    GestureDetector(
                      onTap: () => {},
                      child: Container(
                          //头部搜索框
                          padding: EdgeInsets.all(10),
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(20))),
                          margin: const EdgeInsets.only(
                              left: 10, top: 50, right: 10),
                          height: 35,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Icon(Icons.search, size: 15, color: Colors.grey),
                              Text(Strings.search_goods_hint,
                                  style: TextStyle(
                                      color: Colours.ffafb5bc, fontSize: 12))
                            ],
                          )),
                    ),
                    Consumer<CommonProvider>(
                      //banner
                      builder: (context, provider, child) {
                        return Container(
                          padding: EdgeInsets.only(top: 10),
                          child: BannerPage(
                              200.0,
                              List.generate(
                                  _bannerProvider.list.length,
                                  (index) => Padding(
                                      padding:
                                          EdgeInsets.only(left: 10, right: 10),
                                      child: _bannerProvider.list.isNotEmpty
                                          ? Image.network(_bannerProvider
                                              .list[index].imagePath)
                                          : Image.asset(
                                              'assets/images/splash.jpg')))),
                        );
                      },
                    ),
                    Padding(
                        padding: EdgeInsets.only(left: 10, top: 10),
                        child: Text(
                          '完整项目',
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: 16,
                              fontWeight: FontWeight.bold),
                        )),
                    Consumer<CommonProvider>(
                        builder: (context, provider, child) {
                      return StaggeredGridView.countBuilder(
                        crossAxisCount: 6,
                        crossAxisSpacing: 5,
                        mainAxisSpacing: 5,
                        itemCount: 5,
                        padding: EdgeInsets.all(10),
                        //禁止滑动
                        physics: NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        staggeredTileBuilder: (index) => StaggeredTile.count(
                            index < 2 ? 3 : 2, index < 2 ? 1.8 : 2.4),
                        itemBuilder: (context, index) {
                          return Container(
                            child: _projectProvider.list.isEmpty
                                ? Image.asset(
                                    'assets/images/splash.jpg',
                                    fit: BoxFit.cover,
                                  )
                                : Image.network(
                                    _projectProvider.list[index].envelopePic,
                                    fit: BoxFit.cover,
                                  ),
                          );
                        },
                      );
                    }),
                    Padding(
                        padding: EdgeInsets.only(left: 10, top: 10),
                        child: Text(
                          '热门公众号',
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: 16,
                              fontWeight: FontWeight.bold),
                        )),
                    Consumer<CommonProvider>(
                      builder: (context, provider, widget) => GridView.count(
                          padding: EdgeInsets.all(10),
                          physics: NeverScrollableScrollPhysics(),
                          //禁止滑动
                          shrinkWrap: true,
                          crossAxisCount: 5,
                          crossAxisSpacing: 1,
                          mainAxisSpacing: 1,
                          childAspectRatio: 0.8,
                          children: List.generate(
                              _authorProvider.list.length,
                              (index) => InkWell(
                                    onTap: () =>
                                        RouterUtils.goWXArticleListPage(
                                            context,
                                            _authorProvider.list[index].name,
                                            _authorProvider.list[index].id.toString()),
                                    child: Container(
                                      alignment: Alignment.center,
                                      color: Colours.ff0692ff,
                                      child: Text(
                                          _authorProvider.list[index].name,
                                          textAlign: TextAlign.center,
                                          style:
                                              TextStyle(color: Colors.white)),
                                    ),
                                  ))),
                    ),
                    Padding(
                        padding: EdgeInsets.only(left: 10, top: 10),
                        child: Text(
                          '置顶文章',
                          style: TextStyle(
                              color: Colors.black,
                              fontSize: 16,
                              fontWeight: FontWeight.bold),
                        )),
                    Consumer<CommonProvider>(
                        builder: (context, provider, widget) =>
                            ListView.separated(
                              itemCount: _articleProvider.list.length,
                              shrinkWrap: true,
                              //禁止滑动
                              physics: NeverScrollableScrollPhysics(),
                              itemBuilder: (context, index) =>
                                  ListArticleItem(_articleProvider.list[index]),
                              separatorBuilder: (BuildContext context,
                                      int index) =>
                                  Divider(height: 10, color: Colours.fff1f3f4),
                            ))
                  ]),
            )
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
